import time
import threading

from loguru import logger

from common.db import get_db

from common.db.crud import taobao as taobao_crud
from common.schema.taobao import TaoBaoOrderTask
from tasks.taobao.run import AutoTaoBaoShoppingFsm


class PhoneThread:
    ThreadStatus = {}

    @classmethod
    def set_thread(cls, android_ip, new_thread):
        if cls.check_thread_is_running(android_ip):
            raise Exception("cls.ThreadStatus[{}] is running, can't set new one".format(android_ip))
        cls.ThreadStatus[android_ip] = new_thread

    @classmethod
    def check_thread_is_running(cls, android_ip):
        if android_ip not in cls.ThreadStatus:
            taobao_crud.update_order(next(get_db()), android_ip, {"processing": False})
            return False
        obj = cls.ThreadStatus[android_ip]
        if not isinstance(obj, threading.Thread):
            raise Exception("cls.ThreadStatus[{}] is not thread object".format(android_ip))
        flag = obj.is_alive()
        taobao_crud.update_order(next(get_db()), android_ip, {"processing": flag})
        return flag


def create_phone_task_thread(order_task: TaoBaoOrderTask):
    """

    :param order_task:
    :return:
    """
    android_ip = order_task.android_ip
    db_order = taobao_crud.get_order(next(get_db()), android_ip)
    if not db_order:
        taobao_crud.create_order(next(get_db()), order_task)
    elif db_order.order_id != order_task.order_id:
        taobao_crud.delete_order(next(get_db()), android_ip)
        taobao_crud.create_order(next(get_db()), order_task)
        logger.info("android_ip={} del_id={} create_id={}".format(android_ip, db_order.order_id, order_task.order_id))
        db_order = taobao_crud.get_order(next(get_db()), android_ip)
    else:
        db_order = taobao_crud.update_order(next(get_db()), android_ip, order_task.dict())
    logger.info("android_ip={} current order_id is {}".format(android_ip, db_order.order_id))
    # 如果标记是进行中，直接返回
    if PhoneThread.check_thread_is_running(android_ip):
        logger.warning("android_ip={} thread already running, return".format(android_ip))
        return db_order.to_dict()
    # 如果已经拿到订单编号了，那肯定好了
    if db_order.order_number:
        logger.warning("android_ip={} already complete, return".format(android_ip))
        return db_order.to_dict()
    # 否则，进状态机干活
    work_thread = AutoTaoBaoShoppingFsm(android_ip)
    PhoneThread.set_thread(android_ip, work_thread)
    work_thread.setDaemon(True)
    work_thread.start()
    time.sleep(0.1)
    db_order = taobao_crud.get_order(next(get_db()), android_ip)
    return db_order.to_dict()


def get_all_task_status():
    """

    :param android_ip:
    :return:
    """
    db_orders = taobao_crud.get_orders(next(get_db()))
    for order in db_orders:
        PhoneThread.check_thread_is_running(order.android_ip)
    db_orders = taobao_crud.get_orders(next(get_db()))
    return [order.to_dict() for order in db_orders]

